
// 判断一个可达问题，其次是最优化问题
// 判定是建立在最优化的前提之上
public class CoinsExchange {

	interface CheckType {
		final int Gold = 0;
		final int Siver = 1;
	}

	 int [][] m;
	 int N = 0;
	 boolean flag = true;

	boolean checkNode(int i) {
		if (i==2) {
			if(m[0][2] >= m[1][2]) {
				return true;
			} 
			if(m[0][0]<=m[1][0] && m[0][1]<=m[1][1]) {
				flag = false;
				return false;
			} else {
				m[0][1]-=1;
				m[0][2]+=9;
				//
				N+=1;
				return checkNode(CheckType.Siver);
			}
		}
		if(m[0][i] > m[1][i]) {
			if(m[0][i+1]<m[1][i+1]) {
				int diff = m[1][i+1] - m[0][i+1];
				int tmp = diff/9;
				if (diff % 9 != 0) {
					tmp += 1;
				}
				int downchange = Math.min(m[0][i]-m[1][i], tmp);
				N += downchange;
				//
				m[0][i] -= downchange;
				//
				m[0][i+1] += 9 * downchange;
			}
		}
		
		if (m[0][i] == m[1][i]) {
			checkNode(i+1);
		}
		
		if(m[0][i] < m[1][i]) {
			if(i==1 && m[0][0] > m[1][0]) {
				checkNode(CheckType.Gold);
			}
			
			int diff = m[1][i] - m[0][i];
			// 下往上需要11个来换
			m[0][i+1]-=diff*11;
			m[0][i] = m[1][i];
			//
			N += diff;
			checkNode(i+1);
		}
		return true;
	}

	public int countExchanges(int g1, int s1, int b1, int g2, int s2, int b2) {

		 m = new int[2][3];
		 m[0]= new int[] {g1,s1,b1};
		 m[1]= new int[] {g2,s2,b2};
		 flag=true;
		 N=0;
		 
		 checkNode(CheckType.Gold);
		 if (checkNode(CheckType.Siver) && flag) {
//			 System.out.println(N);
			 return N;
		 } else {
//			 System.out.println("-1");
			 return -1;
		 }
	}

	public static void main(String[] args) {
		CoinsExchange test = new CoinsExchange();
		System.out.println(test.countExchanges(1,0,0,0,0,81));
	}
	
}


